package com.example.end.musicplayer.data;


import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Telephony;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import android.media.MediaPlayer.OnCompletionListener;

import java.util.Random;

public class MusicService extends Service {
    //播放控制命令
    public static final int command_unknown = -1;
    public static final int command_play = 0;
    public static final int command_pause = 1;
    public static final int command_stop = 2;
    public static final int command_resume = 3;
    public static final int command_previous = 4;
    public static final int command_next = 5;
    public static final int command_check_is_playing = 6;
    public static final int command_seek_to = 7;
    public static final int command_random=8;
    //播放器状态
    public static final int status_playing = 0;
    public static final int status_paused = 1;
    public static final int status_stopped = 2;
    public static final int status_completed = 3;
    //广播标识
    public static final String BROADCAST_MUSICSERVICE_CONTROL = "MusicService.ACTION_CONTROL";
    public static final String BROADCAST_MUSICSERVICE_UPDATE_STATUS = "MusicService.ACTION_UPDATE";
    //歌曲序号，从0开始
    private int number = 0;
    private int status;
    //媒体播放类
    private MediaPlayer player = new MediaPlayer();
    //广播接收器
    private CommandReceiver receiver;

    private boolean phone=false;

    @Override
    public void onCreate() {
        super.onCreate();
        bindCommandReceiver();
        status=MusicService.status_stopped;
        TelephonyManager telephonyManager=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(new MyPhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);
        Toast.makeText(this,"MusicService.onCreate()",Toast.LENGTH_SHORT).show();
    }
    private final class MyPhoneListener extends PhoneStateListener{
        public void onCallStateChanged(int state,String incomingNumber)
        {
            switch (state)
            {
                case TelephonyManager.CALL_STATE_RINGING:
                    if(status==MusicService.status_playing)
                    {
                        pause();
                        phone=true;
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    if(phone==true)
                    {
                        resume();
                        phone=false;
                    }
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        if(player!=null)
        {
            player.release();
        }
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    //内部类，接收广播命令，并执行操作
    class CommandReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //获取命令
            int command = intent.getIntExtra("command", command_unknown);
            //执行命令
            switch (command) {
                case command_play:

                    number = intent.getIntExtra("number", 0);
                    play(number);
                    break;
                case command_previous:
                    moveNumberToPrevious();
                    break;
                case command_next:
                    moveNumberToNext();
                    break;
                case command_pause:
                    pause();
                    break;
                case command_stop:
                    stop();
                    break;
                case command_resume:
                    resume();
                    break;
                case command_check_is_playing:
                    if(player!=null&&player.isPlaying())
                    {
                        sendBroadcastOnStatusChanged(MusicService.status_playing);
                    }
                    break;
                case command_unknown:
                case command_seek_to:
                    player.seekTo(intent.getIntExtra("time",0));
                    break;
                case command_random:
                    Random rand=new Random();
                    int i;
                    do{
                        i=rand.nextInt(MusicList.getMusicList().size());
                    }while(i==number);//当i的值和number现在的值相同，则重新给i赋值
                    number=i;
                    play(number);
                    break;
                default:
                    break;
            }
        }
    }
    //当状态发送改变，发送广播
    private void sendBroadcastOnStatusChanged(int status)
    {
        Intent intent=new Intent(BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        intent.putExtra("status",status);
        if(status!=status_stopped)
        {
            intent.putExtra("time",player.getCurrentPosition());
            intent.putExtra("duration",player.getDuration());
            intent.putExtra("number",number);
            intent.putExtra("name",MusicList.getMusicList().get(number).getmusicName());
            intent.putExtra("artist",MusicList.getMusicList().get(number).getmusicArtist());
        }
        sendBroadcast(intent);
    }
    //读取音乐文件
    private void load(int number) {
        try {
            player.reset();
            player.setDataSource(MusicList.getMusicList().get(number).getmusicPath());
            player.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //注册播放完成的监听器
        player.setOnCompletionListener(completionListener);
    }
    //播放结束监听器
    OnCompletionListener completionListener=new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            if(player.isLooping())
            {
                replay();
            }
            else
            {
                sendBroadcastOnStatusChanged(MusicService.status_completed);
            }
        }
    };
    //下一首
    private void moveNumberToNext() {
        //判断是否达到列表底端
        if ((number) == MusicList.getMusicList().size() - 1) {
            Toast.makeText(MusicService.this, "已到达列表底端", Toast.LENGTH_SHORT).show();
        } else {
            ++number;
            play(number);
        }
    }
    //上一首
    private void moveNumberToPrevious()
    {
        //判断是否达到列表顶端
        if(number==0)
        {
            Toast.makeText(MusicService.this,"已到达列表顶端",Toast.LENGTH_SHORT).show();
        }
        else
        {
            --number;
            play(number);
        }
    }
    //播放音乐
    private void play(int number)
    {
        if(player!=null&&player.isPlaying())
        {
            player.stop();
        }
        load(number);
        player.start();
        status=MusicService.status_playing;
        sendBroadcastOnStatusChanged(MusicService.status_playing);//发送状态改变的广播
    }
    //暂停音乐
    private void pause()
    {
        if(player.isPlaying())
        {
            player.pause();
            status=MusicService.status_paused;
            sendBroadcastOnStatusChanged(MusicService.status_paused);
        }
    }
    //停止播放
    private void stop()
    {
        if(status!=MusicService.status_stopped)
        {
            player.stop();
            status=MusicService.status_stopped;
            sendBroadcastOnStatusChanged(MusicService.status_stopped);
        }
    }
    //暂停之后恢复播放
    private void resume()
    {
        player.start();
        status=MusicService.status_playing;
        sendBroadcastOnStatusChanged(MusicService.status_playing);
    }
    //播放完成后重新播放
    private void replay()
    {
        player.start();
        status=MusicService.status_playing;
        sendBroadcastOnStatusChanged(MusicService.status_playing);
    }
    //绑定广播接收器
    private void bindCommandReceiver(){
        receiver=new CommandReceiver();
        //构造一个消息过滤器，当过滤器的action与Intent封装的action相同，接收器启动
        IntentFilter filter=new IntentFilter(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        //注册广播接收器，注册后广播才可以正常工作
        registerReceiver(receiver,filter);
    }

}


